In this demonstration,
you will build a consumer that listens to
messages from RabbitMQ. Unlike the producer, which publishes a single
message and exits, the consumer keeps running to listen for messages
and prints them out. Create the consumer.js file. Inside the consumer.js file, import the AMQP dependencies. Now set up a
connection and create a channel that will receive
messages from the queue. Now declare the queue from which you will consume messages. Declaring the queue is
important because if the consumer starts
before the producer, you can make sure that
the queue exists, since the queue
was given a name. The same queue with the name
will be created when you use the assert queue to check
if the queue exists or not. The name must be similar
to the queue name which you have given in
the producer.js file. Now check if the queue exists using the
assertQueue function. As the queue
information is set up, now consume messages from the queue using the
consume method. The consume method
takes two parameters, name of the queue and a callback function which returns the message
from the queue. The returned message can be
printed out onto the console. The message return is in
the form of a buffer array. Hence, you will
convert the array into a string using
content.toString method. Ensure that the noACK
parameter must be set to true or else the consumer will constantly read messages
from the queue. In order to avoid constantly
reading of the same message, you will set the noACK to true. Which means that once a message
is read from the queue, the message is removed
from the queue. Now the consumer is also ready. Open a terminal and start
the producer to publish messages using
node./producer.js command. As you can see, hello is being published
to the queue on RabbitMQ. Go to RabbitMQ
management and check if the test queue is created and the message is pushed there. Go to the Queues tab. As you can see, the
test queue is created. In the test queue
go to get messages, and you can see that the message hello is
pushed to the queue, but this message is not
yet being consumed. Now start the consumer, open a new terminal and run
the node consumer.js command. The consumer has
read the message and hello is being
printed on screen. Go to the RabbitMQ management to check if the message
has been consumed. The message hello
is still present, but when you go to get messages, it says that the queue is empty. In that case, the message has been consumed by the consumer, and hence there is no
data in the queue. You have created a producer and a consumer and done
message exchange asynchronously using
a message broker like RabbitMQ. Thank you.